package com.caption.core.exception;

import com.caption.core.model.entity.BaseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理器
 *
 * @description: TODO
 * @author: 码农
 * @date: 2022-01-21 22:18:59
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseData exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
        log.error("全局异常拦截器，发生异常:", e);
        BaseData baseData = null;
        if (e instanceof ServiceException) {
            ServiceException exception = (ServiceException) e;
            baseData = new BaseData();
            baseData.setCode(exception.getCode());
            baseData.setMessage(exception.getDesc());
        }

        if (baseData == null) {
            baseData.setData(503);
            baseData.setMessage(e.getMessage());
        }
        return baseData;
    }
}
